package com;

import java.nio.ByteBuffer;

public class StringToHex {
    //16进制字符串转byte数组
    public static byte[] hexStr2Byte(String hex) {
        ByteBuffer bf = ByteBuffer.allocate(hex.length() / 2);
        for (int i = 0; i < hex.length(); i++) {
            String hexStr = hex.charAt(i) + "";
            i++;
            hexStr += hex.charAt(i);
            byte b = (byte) Integer.parseInt(hexStr, 16);
            bf.put(b);
        }
        return bf.array();
    }

    //byte数组转16进制字符串
    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2) {
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    //byte数组转2进制字符串
    public static final String byteArraytoByteString(byte[] bArray) {
        StringBuilder sb = new StringBuilder(bArray.length);
        for (int i = 0; i < bArray.length; i++) {
            byte t = bArray[i];
            StringBuilder tsb = new StringBuilder();
            for (int j=7;j>=0;j--){
                int temp  = 0x01 & t;
                tsb.append(temp);
                t >>=1;
            }
            sb.append(tsb.reverse());
        }
        return sb.toString();
    }

}
